import { ipcRenderer } from "electron";
import fs from "fs";
import http from "http";
import https from "https";
import path from "path";
import { PATH } from "../main/utils";

let uid = "";

export const startServer = () => {
  const server = http.createServer();
  let userStatus = "login";
  server.on("request", (req, res) => {
    res.writeHead(200, {
      "content-type": "text/html;charset=utf8",
    });
    switch (req.url) {
      case "/index.html":
        const data = fs.readFileSync(path.join(PATH.public, "./server.html"));
        res.end(data);
        break;
      case "/cookie":
        getUserInfo(req.headers.cookie);
        res.end("ok");
        break;
      case "/login":
        userStatus = "login";
        res.end(JSON.stringify({ success: true }));
        break;
      case "/logout":
        userStatus = "logout";
        uid = "";
        res.end(JSON.stringify({ success: true }));
        break;
      case "/userStatus":
        res.end(JSON.stringify({ userStatus }));
        break;
      case "/uid":
        res.end(JSON.stringify({ uid }));
        break;
      default:
        res.end("ok");
        break;
    }
  });

  server.listen(5500, () => {
    console.log("5500端口已开启");
  });
};

export const getUserInfo = (cookie) => {
  ipcRenderer.send("close-child");
  const cookies = {};
  cookie.split(";").forEach((co) => {
    const parts = co.split("=");
    cookies[parts[0].trim()] = (parts[1] || "").trim();
  });
  const keys = [
    "hwsso_am",
    "hwsso_login",
    "hwssot",
    "hwssot3",
    "login_logFlag",
    "login_sid",
    "login_sip",
    "login_uid",
    "LtpaToken",
    "w3Token",
  ];
  const token = {};
  keys.forEach((key) => {
    token[key] = cookies[key];
  });
  const loginBody = JSON.stringify({
    token: token,
    url: "w3.huawei.com",
  });
  const options = {
    host: "login.huawei.com",
    port: 443,
    rejectUnauthorized: false, // 忽略证书
    path: "/login/rest/token",
    method: "PUT",
    headers: {
      "Content-Type": "application/json",
      "Cache-Control": "no-cache",
    },
  };
  const req = https.request(options, (res) => {
    res.setEncoding("utf-8");
    let str = "";
    res.on("data", (chunk) => {
      str += chunk;
    });
    res.on("end", () => {
      try {
        const { user } = JSON.parse(str || "{}");
        uid = user.uid;
        ipcRenderer.send("userInfo", user);
      } catch (err) {
        console.log(err);
      }
    });
  });
  req.write(loginBody);
  req.on("error", (err) => {
    console.log(err.message);
  });
  req.end();
};
